<template>
  <div class="main_container">
    <div class="title" v-if="!isMobile">
      <h2>欢迎回来,{{ userInfo.username }}</h2>
      <p>以下是你的综合素质评价记录概览</p>
    </div>
    <!-- 顶部卡片区域 -->
    <record-cards :cardList="cardList" :cardQuery="cardQuery" />
    <!-- 内容区域 -->
    <el-row :gutter="20" class="content-row">
      <el-col :span="16" :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <!-- 表格内容区域 -->
        <table-module :tableQuery="tableQuery" />
      </el-col>

      <el-col :span="8" :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <h3>快捷功能</h3>
            </div>
          </template>
          <div class="quick-functions">

            <div class="function-item" @click="gotoPath('/list')">
              <el-link :underline="false" class="function-link" to="/list">
                <div class="function-icon">
                  <el-icon>
                    <Document />
                  </el-icon>
                </div>
                <div class="function-text">记录管理</div>
              </el-link>
            </div>
            <div class="function-item" @click="gotoPath('/SelfStatement')">
              <el-link :underline="false" class="function-link" to="/SelfStatement">
                <div class="function-icon">
                  <el-icon>
                    <Document />
                  </el-icon>
                </div>
                <div class="function-text">自我陈述</div>
              </el-link>
            </div>
            <div class="function-item" @click="gotoPath('/RecordSelection')">
              <el-link :underline="false" class="function-link" to="/TermPaper">
                <div class="function-icon">
                  <el-icon>
                    <Check />
                  </el-icon>
                </div>
                <div class="function-text">记录遴选</div>
              </el-link>
            </div>
            <div class="function-item" @click="gotoPath('/TermPaper')">
              <el-link :underline="false" class="function-link" to="/TermPaper">
                <div class="function-icon">
                  <el-icon>
                    <PieChart />
                  </el-icon>
                </div>
                <div class="function-text">评价报告</div>
              </el-link>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- echarts展示区域 -->
    <el-row class="image-container" :gutter="20">
      <el-col :span="16" :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card class="image-card">
          <template #header>
            <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
              <h3>综合素质成长趋势</h3>
              <div class="button-row">
                <el-button :type="btnType === 'semester' ? 'primary' : 'default'" size="small" round
                  @click="btnChange('semester')">本学期</el-button>
                <el-button :type="btnType === 'year' ? 'primary' : 'default'" size="small" round
                  @click="btnChange('year')">本年度</el-button>
              </div>
            </div>
          </template>
          <div class="image-wrapper chart" ref="chartRef">
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <!-- 待办事项模块 -->
        <el-card class="todo-card">
          <template #header>
            <div class="card-header">
              <h3>待办事项</h3>
              <span class="todo-count">3项待办</span>
            </div>
          </template>
          <div class="todo-list">
            <div class="todo-item" v-for="(item, index) in todoItems" :key="index">
              <el-checkbox :model-value="false" class="todo-checkbox" />
              <div class="todo-content">
                <div class="todo-title">{{ item.title }}</div>
                <div class="todo-deadline">截止日期: {{ item.deadline }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, reactive } from 'vue';
import "element-plus/dist/index.css";
import recordCards from "@/components/record-cards.vue";
import tableModule from "@/components/table-module.vue";
import { useRouter } from 'vue-router';
import { getStuRows } from '@/api/list.js'
const router = useRouter();

import * as echarts from 'echarts';
// 导入API
import { getSummary } from '@/api/home.js';
import { useStore } from "@/store";
const store = useStore();
const userInfo = computed(() => store.user.userInfo);
const cardList = reactive([]);
const recordStore = store.record;
const homeStore = store.home;

// 卡片参数
const cardQuery = {
  borderRadius: '10px',
  type: 'home',
};


// 表格数据参数
const tableQuery = reactive({
  page: 1,
  size: 5,
  total: computed(() => recordStore.filters.listPage.filteredTotal),
  small: false,
  title: '个人经历',
  list: computed(() => recordStore.records),
  isLoading: recordStore.isLoading,
  cz: false,
  columns: [
    {
      prop: 'EVALRECORD',
      label: '记录标题',
      width: '160'
    },
    {
      prop: 'PARENT_NAME',
      label: '类型',
      width: '100'
    },
    {
      prop: 'TJRQ',
      label: '日期',
      width: '120'
    },
    {
      prop: 'FLAG',
      label: '状态',
      width: '100'
    }
  ]
});

// 待办事项数据
const todoItems = [
  {
    title: "完成本月思想品德记录",
    deadline: "2023-05-31",
  },
  {
    title: "提交期中自我陈述",
    deadline: "2023-06-05",
  },
  {
    title: "遴选本学期优秀记录",
    deadline: "2023-06-10",
  },
];
let btnType = ref('semester');

const gotoPath = (path) => {
  router.push(path);
  // 刷新页面
  // window.location.reload();
}

// const btnChange = (type) => {
//   if (type === 'semester') {
//     // 执行本学期按钮点击事件
//     btnType.value = type;
//   } else if (type === 'year') {
//     // 执行本年度按钮点击事件
//     btnType.value = type;
//   }
// }


// 仪表盘卡片数据
const getSummaryData = () => {
  getSummary().then(res => {
    const { code, data } = res;
    if (code > 0) {
      cardList.push(...data);
    }
  }).catch(err => {
    console.log(err);
  });
};

// 1. 获取图表容器DOM
const chartRef = ref(null);
// 2. 存储图表实例（方便后续销毁）
let myChart = null;

// const generateChartData = (records, semesters, filterType = 'year') => {
//   console.log('semesters', semesters);
//   const data = []; // 存储图表数据
//   const semesterData = []; // 存储学期数据
//   const yearData = []; // 存储年度数据
//   const now = new Date();
//   let currentSemester = null;
//   if (filterType === 'year') {
//     startDate = new Date(now.getFullYear(), 0, 1);
//     endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
//   } else { // 默认为学期
//     currentSemester = semesters.find(s => {
//       const begin = new Date(s.BEGINDATE);
//       const end = new Date(s.ENDDATE);
//       return now >= begin && now <= end;
//     })
//     if (!currentSemester) {
//       const sortedSemesters = [...semesters].sort((a, b) => new Date(a.BEGINDATE) - new Date(b.BEGINDATE));
//       currentSemester = sortedSemesters.filter(s => new Date(s.ENDDATE) < now).pop();
//       if (!currentSemester) {
//         currentSemester = sortedSemesters.find(s => new Date(s.BEGINDATE) > now);
//       }
//     }
//     if (currentSemester) {
//       startDate = new Date(currentSemester.BEGINDATE);
//       endDate = new Date(currentSemester.ENDDATE);
//     } else {
//       startDate = new Date(now.getFullYear(), 0, 1);
//       endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
//     }
//   }
// }

// 3. 图表配置项（可改为响应式数据，便于动态更新）

// 修改generateChartData函数，实现数据处理逻辑
const generateChartData = (records, semesters, filterType = 'semester') => {

  const now = new Date();
  let startDate = null;
  let endDate = null;
  let currentSemester = null;

  // 确定日期范围
  if (filterType === 'year') {
    startDate = new Date(now.getFullYear(), 0, 1);
    endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
  } else { // 学期
    // 查找当前学期
    currentSemester = semesters.find(s => {
      const begin = new Date(s.BEGINDATE);
      const end = new Date(s.ENDDATE);
      return now >= begin && now <= end;
    });

    // 如果没有找到当前学期，使用最近的学期
    if (!currentSemester) {
      const sortedSemesters = [...semesters].sort((a, b) => new Date(a.BEGINDATE) - new Date(b.BEGINDATE));
      currentSemester = sortedSemesters.filter(s => new Date(s.ENDDATE) < now).pop();
      if (!currentSemester) {
        currentSemester = sortedSemesters.find(s => new Date(s.BEGINDATE) > now);
      }
    }

    if (currentSemester) {
      startDate = new Date(currentSemester.BEGINDATE);
      endDate = new Date(currentSemester.ENDDATE);
    } else {
      startDate = new Date(now.getFullYear(), 0, 1);
      endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
    }
  }

  // 获取学期内的所有月份
  const months = getMonthsBetweenDates(startDate, endDate);

  // 按月份和指标类型分组统计
  const dataByMonthAndType = {};
  const indicatorTypes = ['思想发展', '学业发展', '身心发展', '审美素养', '劳动与社会实践'];

  // 初始化数据结构
  months.forEach(month => {
    dataByMonthAndType[month] = {
      '思想发展': 0,
      '学业发展': 0,
      '身心发展': 0,
      '审美素养': 0,
      '劳动与社会实践': 0
    };
  });

  // 处理记录数据
  records.forEach(record => {
    // 确保记录有日期和类型信息
    if (!record.TJRQ || !record.PARENT_NAME) return;

    const recordDate = new Date(record.TJRQ);
    // 检查记录是否在日期范围内
    if (recordDate >= startDate && recordDate <= endDate) {
      const monthKey = recordDate.getMonth() + 1 + '月';

      // 根据PARENT_NAME将记录归类到对应的指标类型
      if (record.PARENT_NAME.includes('品德')) {
        if (dataByMonthAndType[monthKey]) {
          dataByMonthAndType[monthKey]['思想发展']++;
        }
      } else if (record.PARENT_NAME.includes('学业')) {
        if (dataByMonthAndType[monthKey]) {
          dataByMonthAndType[monthKey]['学业发展']++;
        }
      } else if (record.PARENT_NAME.includes('身心')) {
        if (dataByMonthAndType[monthKey]) {
          dataByMonthAndType[monthKey]['身心发展']++;
        }
      } else if (record.PARENT_NAME.includes('审美')) {
        if (dataByMonthAndType[monthKey]) {
          dataByMonthAndType[monthKey]['审美素养']++;
        }
      } else if (record.PARENT_NAME.includes('劳动')) {
        if (dataByMonthAndType[monthKey]) {
          dataByMonthAndType[monthKey]['劳动与社会实践']++;
        }
      }
    }
  });

  // 生成ECharts需要的数据格式
  const xAxisData = Object.keys(dataByMonthAndType).sort((a, b) => {
    const monthA = parseInt(a.replace('月', ''));
    const monthB = parseInt(b.replace('月', ''));
    return monthA - monthB;
  });

  const seriesData = indicatorTypes.map(type => {
    return {
      name: type,
      type: 'line',
      data: xAxisData.map(month => dataByMonthAndType[month][type] || 0),
      // 为了匹配效果图的样式，我们设置合适的线条样式
      smooth: true,
      lineStyle: {
        width: 3
      },
      // 可以添加一些默认值，确保图表即使没有数据也能显示基础趋势
      markLine: {
        silent: true,
        lineStyle: {
          color: '#999'
        },
        data: [{ yAxis: 0 }]
      }
    };
  });

  // 更新图表配置
  chartOption.value = {
    title: {
      text: '综合素质成长趋势'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: indicatorTypes
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: xAxisData
      }
    ],
    yAxis: [
      {
        type: 'value',
        min: 0,
        max: 5,
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: seriesData
  };

  // 如果图表实例已存在，更新图表
  if (myChart) {
    myChart.setOption(chartOption.value);
    adaptChartForMobile();
  }
};


// 辅助函数：获取两个日期之间的所有月份
const getMonthsBetweenDates = (startDate, endDate) => {
  const months = [];
  const currentDate = new Date(startDate);

  while (currentDate <= endDate) {
    const monthKey = currentDate.getMonth() + 1 + '月';
    if (!months.includes(monthKey)) {
      months.push(monthKey);
    }
    currentDate.setMonth(currentDate.getMonth() + 1);
  }

  return months;
}

// 修改btnChange函数，添加数据刷新逻辑
const btnChange = (type) => {
  btnType.value = type;
  // 切换类型时重新生成图表数据
  if (recordStore.records && homeStore.semesterInfo) {
    generateChartData(recordStore.records, homeStore.semesterInfo, type);
  }
};


const chartOption = ref({
  title: {
    text: '综合素质成长趋势'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: ['2月', '3月', '4月', '5月', '6月']
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: 'Union Ads',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: 'Video Ads',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [150, 232, 201, 154, 190, 330, 410]
    },
    {
      name: 'Direct',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [320, 332, 301, 334, 390, 330, 320]
    },
    {
      name: 'Search Engine',
      type: 'line',
      stack: 'Total',
      label: {
        show: true,
        position: 'top'
      },
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [820, 932, 901, 934, 1290, 1330, 1320]
    }
  ]
});

// 监听窗口大小变化，自动调整图表尺寸
const handleResize = () => {
  myChart?.resize();
  adaptChartForMobile(); // 初始化时调用适配函数
};

// 4. 初始化图表（在DOM挂载后执行）
onMounted(async () => {
  // 获取当前学期信息并设置可操作学期
  store.home.getSemesterData().then(() => {
    // 获取学期信息
    const semesterInfo = store.home.getSemesterInfo
    if (semesterInfo && semesterInfo.length > 0) {
      // 实际项目中应该根据业务逻辑判断哪个学期是当前可操作的
      const currentSemesterId = semesterInfo[semesterInfo.length - 1].SEMESTER_ID
      // 设置当前可操作学期
      store.settings.setCurrentOperableSemester(currentSemesterId)
      // 也可以设置可操作学期列表
      store.settings.setOperableSemesters([currentSemesterId])
    }
  })

  // 获取仪表盘卡片数据
  getSummaryData();

  // 调用API获取最近记录数据
  getStuRows().then(res => {
    recordStore.records = res
  })

  // 获取学期信息
  await homeStore.getSemesterData();
  // generateChartData(recordStore.records, homeStore.semesterInfo)
  // 初始化图表实例
  myChart = echarts.init(chartRef.value);
  // 设置图表配置
  // myChart.setOption(chartOption.value);
  // 生成并设置图表数据
  if (recordStore.records && homeStore.semesterInfo) {
    generateChartData(recordStore.records, homeStore.semesterInfo);
  } else {
    // 如果没有数据，设置默认配置
    myChart.setOption(chartOption.value);
  }
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 监听学期信息变化
watch(
  () => homeStore.semesterInfo,
  (newSemesterInfo) => {
    if (Object.keys(newSemesterInfo).length > 0) {
      // 在这里处理数据变化后的逻辑
    }
  },
  { deep: true }
);
// 5. 监听配置项变化，动态更新图表（可选）
watch(
  chartOption,
  (newVal) => {
    myChart?.setOption(newVal); // 配置项变化时重新渲染图表
  },
  { deep: true } // 深度监听对象内部变化
);

// 修改监听，当记录数据变化时更新图表
watch(
  () => recordStore.records,
  (newRecords) => {
    if (newRecords && newRecords.length > 0 && homeStore.semesterInfo) {
      generateChartData(newRecords, homeStore.semesterInfo, btnType.value);
    }
  },
  { deep: true }
);

// 6. 组件卸载时销毁图表（防止内存泄漏）
onUnmounted(() => {
  if (myChart) {
    myChart.dispose(); // 销毁图表实例
    myChart = null;
    window.removeEventListener('resize', handleResize); // 移除窗口大小变化监听
  }
});

// 7. 移动端适配函数
const adaptChartForMobile = () => {
  const isMobile = window.innerWidth < 768;
  const newOption = {
    ...chartOption.value,
    // 移动端简化图例
    legend: isMobile ? {
      data: chartOption.value.legend.data,
      bottom: 0,
      textStyle: { fontSize: 12 }
    } : chartOption.value.legend,
    // 移动端调整标题
    title: isMobile ? {
      text: chartOption.value.title.text,
      textStyle: { fontSize: 14 }
    } : chartOption.value.title,
    // 移动端调整tooltip
    tooltip: isMobile ? {
      ...chartOption.value.tooltip,
      trigger: 'axis',
      axisPointer: { type: 'line' }
    } : chartOption.value.tooltip
  };
  myChart.setOption(newOption);
};



</script>

<style scoped lang="scss">
/* 原有样式保持不变 */
.main_container {
  width: 100%;
  max-width: 1450px;
  margin: 0 auto;
  padding: 0;

  .title {
    max-width: 1420px;
    margin: 0 auto;

    h2 {
      font-size: 24px;
      font-weight: 800;
      margin: 10px 0;
    }

  }

  .content-row {
    ::v-deep>div.is-guttered {
      margin: 10px 0;
    }

    .box-card {
      height: 100%;
      box-shadow: $base-box-shadow;
      border-radius: 10px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }


      .quick-functions {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        padding: 15px;

        .function-item {
          width: calc(50% - 10px);
          display: flex;
          justify-content: center;
          align-items: center;

          .function-link {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 15px;
            border-radius: 10px;
            background-color: #f0f2f5;
            width: 100%;
            height: 100%;

            .function-icon {
              font-size: 24px;
              color: $base-color-primary;
              margin-bottom: 10px;
              display: contents;
            }

            .function-text {
              font-size: $base-font-size-default;
              color: $base-color-6;
            }
          }

          .function-link:hover {
            background-color: #e9ebec;
          }
        }

      }

      ::v-deep .el-table .el-table__body,
      ::v-deep .el-table .el-table__header {
        width: 100% !important;
      }
    }

    .status-tag {
      display: inline-block;
      padding: 2px 8px;
      background-color: $base-color-green;
      color: $base-color-white;
      border-radius: 12px;
      font-size: $base-font-size-small;
    }
  }

  .image-container {
    margin: 10px 0;

    ::v-deep .el-row .el-col {
      padding-bottom: 10px;
    }
  }

  .record-cards {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;

    .card-item {
      width: calc(25% - 10px);
      flex: 1;
      min-width: 300px;
    }
  }

  .chart-container {
    width: 100%;
    height: 100%;
    min-width: 600px;
    /* 最小宽度，避免图表过窄 */
    min-height: 500px;
    /* 最小高度，确保图表可见 */
    padding: 10px;
    box-sizing: border-box;
  }

  .chart {
    width: 100%;
    height: 100%;
  }

  .image-card {
    height: 100%;
    display: flex;
    flex-direction: column;

    .image-wrapper {
      flex: 1;
      min-height: 400px;
      /* 确保有足够的高度 */
      width: 100%;

      .responsive-image {
        width: 100%;
        height: 100%;
      }

      .image-error {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #909399;
      }
    }
  }

  // 待办事项卡片样式
  .todo-card {
    margin: 0;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0px 20px;

      .todo-count {
        background-color: #f56c6c;
        color: white;
        font-size: 12px;
        padding: 2px 8px;
        border-radius: 10px;
      }
    }

    .todo-list {
      padding: 0px 20px;

      .todo-item {
        display: flex;
        align-items: flex-start;
        padding: 10px 0;

        &:last-child {
          border-bottom: none;
        }

        .todo-checkbox {
          margin-top: 4px;
          margin-right: 12px;
        }

        .todo-content {
          flex: 1;

          .todo-title {
            font-size: 14px;
            color: #303133;
            margin-bottom: 4px;
          }

          .todo-deadline {
            font-size: 12px;
            color: #909319;
          }
        }
      }
    }
  }
}

/* 平板到手机过渡区间 (768px --1148px) */
@media (max-width: 1148px) {
  .main_container {
    .record-cards {
      flex-wrap: wrap;
      gap: 15px;
      justify-content: center;

      .card-item {
        width: calc(50% - 10px);
        flex: none;
        min-width: 200px;
      }
    }

    .image-card {
      .image-wrapper {
        height: 350px;
      }
    }
  }
}

/* 手机屏幕 (<= 768px) */
@media (max-width: 768px) {
  .main_container {
    .title{
      padding: 0 15px;
      h2{
        font-size: 28px;
      }
      p{
        font-size: 15px;
      }
    }
    .record-cards {
      .card-item {
        width: 100%;
        min-width: auto;
      }
    }

    .image-card {
      .image-wrapper {
        min-height: 300px;
        /* 移动端减少高度 */
      }

      .card-header h3 {
        font-size: 14px;
        /* 移动端标题缩小 */
      }

      .card-header p {
        font-size: 10px;
        /* 移动端标题缩小 */
      }

    }

    .box-card {
      .quick-functions {
        .function-item {
          width: 100%;
        }
      }
    }

    .campus-card {
      .campus-gallery {
        .gallery-row {
          .gallery-image {
            height: 80px;
          }
        }
      }
    }

    ::v-deep .el-table .el-table__cell {
      padding: 8px 4px;
      font-size: $base-font-size-small;
    }
  }

  .image-container {
    margin: 10px 0;
    .el-col {
      padding-bottom: 10px;
    }
  }
}

/* 小屏幕手机适配 */
@media screen and (max-width: 480px) {
  .image-wrapper {
    min-height: 200px;
    /* 小屏幕进一步减少高度 */
  }
}
</style>
